package cn.cdu.doctor.controller;

import cn.cdu.basics.baseVo.PageVo;
import cn.cdu.basics.baseVo.Result;
import cn.cdu.basics.utils.PageUtil;
import cn.cdu.basics.utils.ResultUtil;
import cn.cdu.data.utils.NullUtils;
import cn.cdu.doctor.entity.Doctor;
import cn.cdu.doctor.entity.DoctorScheduling;
import cn.cdu.doctor.service.IDoctorSchedulingService;
import cn.cdu.doctor.service.IDoctorService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@Tag(name = "医生排班管理")
@RequestMapping("/zwz/doctorScheduling")
@Transactional
public class DoctorSchedulingController {

    @Autowired
    private IDoctorSchedulingService iDoctorSchedulingService;

    @Autowired
    private IDoctorService iDoctorService;

    @RequestMapping(value = "/addNumber", method = RequestMethod.POST)
    @Operation(summary = "医生放号")
    public Result<Object> addNumber(@RequestBody Map<String, Object> params) {
        String doctorId = (String) params.get("doctorId");
        String date = (String) params.get("date");
        int step = Integer.parseInt(params.get("step").toString());
        int number = Integer.parseInt(params.get("number").toString());
        
        Doctor doctor = iDoctorService.getById(doctorId);
        if (doctor == null) {
            return ResultUtil.error("医生不存在");
        }
        if (number < 1) {
            return ResultUtil.error("放号数必须大于0");
        }

        // 验证日期格式和有效性
        try {
            LocalDate scheduleDate = LocalDate.parse(date);
            LocalDate today = LocalDate.now();
            if (scheduleDate.isBefore(today)) {
                return ResultUtil.error("不能为过去的日期放号");
            }
        } catch (DateTimeParseException e) {
            return ResultUtil.error("日期格式不正确，请使用YYYY-MM-DD格式");
        }

        // 检查是否已经存在该日期的排班
        QueryWrapper<DoctorScheduling> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("doctor_id", doctorId)
                   .eq("date", date)
                   .eq("step", step);
        long count = iDoctorSchedulingService.count(queryWrapper);
        if (count > 0) {
            return ResultUtil.error("该日期此时段已有排班，请勿重复放号");
        }

        // 批量保存排班记录
        List<DoctorScheduling> schedulingList = new ArrayList<>();
        for (int i = 1; i <= number; i++) {
            DoctorScheduling ds = new DoctorScheduling();
            ds.setDoctorId(doctor.getId());
            ds.setDoctorName(doctor.getDoctorName());
            ds.setNumber(i + "");
            ds.setStep(step + "");
            ds.setDate(date);
            ds.setOrderFlag(0);
            schedulingList.add(ds);
        }
        
        try {
            iDoctorSchedulingService.saveBatch(schedulingList);
            return ResultUtil.success("放号成功");
        } catch (Exception e) {
            return ResultUtil.error("放号失败：" + e.getMessage());
        }
    }

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @Operation(summary = "查询所有医生排班")
    public Result<List<DoctorScheduling>> getAll() {
        return new ResultUtil<List<DoctorScheduling>>().setData(iDoctorSchedulingService.list());
    }

    @RequestMapping(value = "/getByPage", method = RequestMethod.GET)
    @Operation(summary = "查询医生排班")
    public Result<IPage<DoctorScheduling>> getByPage(@ModelAttribute DoctorScheduling scheduling, @ModelAttribute PageVo page) {
        QueryWrapper<DoctorScheduling> qw = new QueryWrapper<>();
        if (!NullUtils.isNull(scheduling.getDoctorId())) {
            qw.eq("doctor_id", scheduling.getDoctorId());
        }
        if (!NullUtils.isNull(scheduling.getDate())) {
            qw.eq("date", scheduling.getDate());
        }
        if (scheduling.getStep().equals("0")) {
            qw.eq("step", "0");
        } else if (scheduling.getStep().equals("1")) {
            qw.eq("step", "1");
        }
        return new ResultUtil<IPage<DoctorScheduling>>().setData(iDoctorSchedulingService.page(PageUtil.initMpPage(page), qw));
    }

    @RequestMapping(value = "/insertOrUpdate", method = RequestMethod.POST)
    @Operation(summary = "增改医生排班")
    public Result<DoctorScheduling> saveOrUpdate(DoctorScheduling doctorScheduling) {
        if (iDoctorSchedulingService.saveOrUpdate(doctorScheduling)) {
            return new ResultUtil<DoctorScheduling>().setData(doctorScheduling);
        }
        return ResultUtil.error();
    }

    @RequestMapping(value = "/delByIds", method = RequestMethod.POST)
    @Operation(summary = "删除医生排班")
    public Result<Object> delAllByIds(@RequestParam String[] ids) {
        for (String id : ids) {
            iDoctorSchedulingService.removeById(id);
        }
        return ResultUtil.success();
    }
}